﻿#region

using System;
using System.Windows.Forms;

#endregion

namespace GGEditor.API.Utility.Forms
{
    public class VisualUpdate : IDisposable
    {
        private readonly Control _control;

        //bool _wasEnabled;
        private bool _disposed;
        private bool _wasFocused;

        public VisualUpdate(Control control)
        {
            _control = Contract.NotNull(control, "control");

            lock (this) {
                //_wasEnabled = Control.Enabled;
                _wasFocused = Control.Focused;
                User32.SendMessage(Control.Handle, (int) WM.SETREDRAW, (IntPtr) 0, (IntPtr) 0);
                Control.SuspendLayout();
                Control.Enabled = false;
            }
        }

        public Control Control
        {
            get { return _control; }
        }

        #region IDisposable Members

        public void Dispose()
        {
            lock (this) {
                if (_disposed)
                    return;
                _disposed = true;
                User32.SendMessage(Control.Handle, (int) WM.SETREDRAW, (IntPtr) 1, (IntPtr) 0);
                Control.Enabled = true;
                //Control.Enabled = _wasEnabled;
                Control.ResumeLayout(true);
                Control.PerformLayout();
                if (_wasFocused)
                    Control.Focus();
                Control.Invalidate(true);
            }
        }

        #endregion
    }
}